﻿using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Controllers
{
    public class ErrorController : Controller
    {
        private readonly ILogger<ErrorController> logger;

        public ErrorController(ILogger<ErrorController> logger)
        {
            this.logger = logger;
        }

        [Route("/Error/ErrorHandler/{code:int}")]
        public IActionResult HandleError(int code)
        {
            ViewData["ErrorMessage"] = $"Error occurred. The ErrorCode is: {code}";
            return View("~/Views/Error/404.cshtml");
        }

        [Route("Error")]
        public IActionResult DefaultHandler()
        {
            // 获取异常信息
            var e = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            // 异常信息写入日志
            logger.LogError($"Exception path: {e.Path}\nException message: {e.Error.Message}\nstack Trace: {e.Error.StackTrace}");

            // 异常信息写入view
            ViewBag.ExceptionPath = e.Path;
            ViewBag.ExceptionMessage = e.Error.Message;
            ViewBag.StackTrace = e.Error.StackTrace;

            return View("Error");
        }
    }
}
